package com.intpro.demo.Service;

import com.intpro.demo.DAO.SearchHistory;
import com.intpro.demo.DAO.User;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class SearchHistoryService
{

	@Autowired
	private MongoTemplate mongoTemplate;

	public void add(User u, String content)
	{
		Query q = new Query(Criteria.where("uid").is(u.id));
		SearchHistory searchHistory = mongoTemplate.findOne(q, SearchHistory.class);
		if (searchHistory == null)
		{
			searchHistory = new SearchHistory();
			searchHistory.uid = u.id;
			searchHistory.content = new LinkedList<>();
		}
		searchHistory.content.add(content);
		if (searchHistory.content.size() > 8)
		{
			searchHistory.content.remove(0);
		}
		mongoTemplate.save(searchHistory);
	}

	public List<String> find(User u)
	{
		Query q = new Query(Criteria.where("uid").is(u.id));
		SearchHistory searchHistory = mongoTemplate.findOne(q, SearchHistory.class);
		return searchHistory.content;
	}

}
